function showLoader(){
  $(".login").children().hide();
  $(".login #loaderHolder, .login #label").show();  

}

function showFields(){
  $(".login").children().show();
  $(".login #loaderHolder").hide();
}

function getFieldsAsJSON(){
  return {
  		usuario   : $("input[name='usuario']").val(), 
      	senha     : $("input[name='senha']").val(), 
      	tipoUsuario : $("select[name='tipoUsuario']").val(),
      	id 			: $("input[name=id]").val(),
       };
}

var start = {
	actions : function() {
		$('input[name="registrar"]').click(function () {
			postCreateUser();
		});

		$('input[name="logar"]').click(function(){
			doLogin();
		});

		$('input[name=refresh]').click(function(){
			getUsers();
		});

		if($("table#usuarios").length > 0){
			getUsers();
		}

    if($("select[name='tipoUsuario']").length > 0){
      getAllTipoUsarios();
    }

	}
};

$(document).ready(start.actions);

function doLogin(){

  $.ajax({
      type: "POST",
      url: "/login/service/login-user",
      data: getFieldsAsJSON()
  }).done(function(data, msg, jqXHR ) {
      //showFields();

      if(data.success == true){

        postLoginUser(data.usuario);

      }else{
        showMessage("error-message", data.message);
      }      

    }).fail(function(jqXHR, textStatus ){
      showFields();
      showMessage("Erro ao tentar realizar o login!\n" + textStatus, "error-message");
    });

}

function postLoginUser(usuario){
  $.ajax({
      type: "POST",
      url: "/sistema/usuario/login-redirect.php",
      data: usuario
  }).done(function(data, msg, jqXHR ) {

    window.location.href = data.split("\"").join("");

  }).fail(function(jqXHR, textStatus ){
      showFields();
      showMessage("Erro ao tentar realizar o login!\n" + textStatus, "error-message");
  });
}

function showMessage(elementClass, message){
  $("div#messages")
          .hide()
          .attr("class", "")
          .addClass(elementClass)
          .html(message)
          .fadeIn(1000)
          .delay(3000)
          .fadeOut(1000);
}


function cleanUSersTable(){
  var $table = $("table#usuarios");
  var $body = $table.children("tbody");
  $body.html('');
}

function updateTable(users){

  var $table = $("table#usuarios");
  var jsonUsers = users;
  var $body = $table.children("tbody");

  $body.html('');

  var rows = '';

  for(var contador = 0; contador < jsonUsers.length; contador++){
    rows += '<tr>';
    rows += '<th>';
    rows += createDeleteButton(jsonUsers[contador].id);
    rows += createUpdateButton(jsonUsers[contador].id);
    rows += '</th>';
    rows += '<th>';
    rows += jsonUsers[contador].user;
    rows += '</th>';
    rows += '<th>';
    rows += jsonUsers[contador].tipoUsuario;
    rows += '</th>';
    rows += '</tr>';
  }

  $body.append(rows);

}

function getUsers(){
  showFullScreenLoader();
  $.ajax({
      type: "POST",
      url: "/login/service/get-all-user",
      data: getFieldsAsJSON()
  }).done(function(data, msg, jqXHR ) {
     if(data.usuarios != undefined && data.usuarios.length > 0){
      updateTable(data.usuarios);
     }else{
      cleanUSersTable();
     }
    }).fail(function(jqXHR, textStatus ){
      console.log(textStatus);
    }).always(function(){
      buildBinds();
      hideFullScreenLoader();
    });
}

function showFullScreenLoader(){
  $('#full-screen-loader').show();
}


function hideFullScreenLoader(){
  $('#full-screen-loader').hide();
}

function createDeleteButton(id){
  return '<a href="#" data-id="'+ id + '" class=" delete-btn btn btn-warning" ><i class="icon-trash"></i> Deletar </a>';
}

function createUpdateButton(id){
  return '<a href="#" data-id="'+ id + '" class=" update-btn btn btn-warning" ><i class="icon-trash"></i> Atualizar </a>';
}

function deleteUser(id){
  showFullScreenLoader();

  $.ajax({
      type: "POST",
      url: "/login/service/delete-user",
      data: {'id' : id}
  }).done(function(data, msg, jqXHR ) {
      var cssClass = data.success == true ? "success-message" : "error-message";
      showMessage(cssClass, data.message);
      getUsers();
    }).fail(function(jqXHR, textStatus ){
      console.log(textStatus);
      showMessage("error-message", "Erro ao deletar o usuario: " + textStatus);
      getUsers();
    });
}

function bindDeleteButton(){
  $('.delete-btn').each(function(){
    $(this).click(function(e){
      e.preventDefault();
      deleteUser($(this).attr('data-id'));
    });
  })
 
}

function bindUpdateButton(){
  $('.update-btn').each(function(){
    $(this).click(function(e){
      e.preventDefault();
      updateUser($(this).attr('data-id'));
    });
  })
}

function buildBinds(){
  bindUpdateButton();
  bindDeleteButton();
}

function updateUser(id){
  showFullScreenLoader();
  $.ajax({
      type: "GET",
      url: "/sistema/usuario/update.html"
  }).done(function(data, msg, jqXHR ) {
     $('body').html('').html(data);
     buldUpdateScreen(id);
    }).fail(function(jqXHR, textStatus ){
      console.log(textStatus);
    }).always(function(){
      hideFullScreenLoader();
    });
}

function buldUpdateScreen(id){

	showFullScreenLoader();

	$.ajax({
		type: "GET",
		url: "/login/service/get-all-tipo-usuario",
	}).done(function(data, msg, jqXHR ) {
		var $tipo = $("select[name='tipoUsuario']");
		var opcoes = '';
		$.each(data.tiposUsuario, function(){
			opcoes += buildOption(this.id, this.nome);
		});

		$tipo.html('').html(opcoes);

    $('input[name="update"]').click(function(){
        postUpdateUser();
    });

		loadUserData(id);
	}).fail(function(jqXHR, textStatus ){
		console.log(textStatus);
	}).always(function(){
		hideFullScreenLoader();
	});
}

function buildOption(value, label){
	return '<option value="' + value + '">' + label + '</option>';
}

function loadUserData(id){

	showLoader();

	$.ajax({
		type: "POST",
		url: "/login/service/get-user-by-id",
		data: {'id' : id}
	}).done(function(data, msg, jqXHR ) {
		var user = data;
		$('input[name=usuario]').val(user.user);
		$('select[name=tipoUsuario]').val(user.tipoUsuarioId);
		$('input[name=id]').val(user.id);
	}).fail(function(jqXHR, textStatus ){
		console.log(textStatus);
	}).always(function(){
		showFields();
	});
}


function postUpdateUser(){
	showLoader();
	$.ajax({
		type: "POST",
		url: "/login/service/update-user",
		data: getFieldsAsJSON()
	}).done(function(data, msg, jqXHR ) {
		var cssClass = data.success == true ? "success-message" : "error-message";
      	showMessage(cssClass, data.message);
	}).fail(function(jqXHR, textStatus ){
		showMessage("error-message", "Ocorreu um erro: " + textStatus);
	}).always(function(){
		showFields();
	});
}

function getAllTipoUsarios(){

  showFullScreenLoader();

  $.ajax({
    type: "GET",
    url: "/login/service/get-all-tipo-usuario",
  }).done(function(data, msg, jqXHR ) {
    var $tipo = $("select[name='tipoUsuario']");
    var opcoes = '';
    $.each(data.tiposUsuario, function(){
      opcoes += buildOption(this.id, this.nome);
    });
    $tipo.html('').html(opcoes);
  }).fail(function(jqXHR, textStatus ){
    console.log(textStatus);
  }).always(function(){
    hideFullScreenLoader();
  });
}

function postCreateUser(){
  showLoader();
  $.ajax({
    type: "POST",
    url: "/login/service/create-user",
    data: getFieldsAsJSON()
  }).done(function(data, msg, jqXHR ) {
    var cssClass = data.success == true ? "success-message" : "error-message";
        showMessage(cssClass, data.message);
  }).fail(function(jqXHR, textStatus ){
    showMessage("error-message", "Ocorreu um erro: " + textStatus);
  }).always(function(){
    showFields();
  });
}
